package com.localcache.server.init;

import com.localcache.server.handler.CacheServerHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import com.localcache.server.handler.JvmMemoryHandler;
import io.netty.util.CharsetUtil;

/**
 * netty 启动 初始化的 channelHandler
 *
 * @author chennengcheng
 * @date 2021-09-14 9:41
 * @remark
 */
public class LocalCacheServerInitializer extends ChannelInitializer<SocketChannel>{

	private CacheServerHandler cacheServerHandler;

	private JvmMemoryHandler jvmMemoryHandler;

	public LocalCacheServerInitializer() {
		this.cacheServerHandler = new CacheServerHandler();
		this.jvmMemoryHandler = new JvmMemoryHandler();
	}

	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();
		pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
		pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
		// 必须放在后面，因为有解码得问题
		pipeline.addLast("jvmMemoryHandler", this.jvmMemoryHandler);
		pipeline.addLast("cacheServerHandler", this.cacheServerHandler);
		pipeline.addLast(new LengthFieldPrepender(4));
		pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));

	}
}